﻿using JGSoft.U9CRTAPIEX.Public;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using UFIDA.U9.SM.SO;
using UFIDA.U9.SM.SOModify.Proxy;
using UFIDA.U9.SM.SOModify;
using UFSoft.UBF.AopFrame.Lock;
using UFSoft.UBF.MVC.Common;
using JGSoft.U9CRTAPIEX.DTOs.RequestDTOs;
using UFIDA.U9.Sn;
using UFIDA.U9.Sn.Proxy;
using UFIDA.U9.Base.Organization;
using UFIDA.U9.PM.Rcv;
using UFIDA.U9.CBO.SCM.Item;
using UFIDA.U9.Base.PropertyTypes;
using System.Collections;
using Newtonsoft.Json;
using UFIDA.U9.CBO.MFG.PMM;
using UFSoft.UBF.Business;
using UFSoft.UBF.Util.Context;
using UFIDA.U9.ISV.SM.Proxy;
using UFIDA.U9.ISV.SM;

namespace JGSoft.U9CRTAPIEX.Controllers
{
    public class KLWController : ApiController
    {
        private readonly string _userCode;
        private readonly string _entCode;
        private string _orgCode;
        public KLWController()
        {
            JsonConfig _config = new JsonConfig();
            _userCode = _config.SelectToken("UserCode");
            _entCode = _config.SelectToken("EntCode");
            _orgCode = _config.SelectToken("OrgCode");
        }
        /// <summary>
        /// 销售变更单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult<string> SOModify(SOModifyPara para)
        {
            using (BPForEngine bp1 = new BPForEngine())
            {
                PublicMethod.WriteContext(para.context.UserCode, para.context.EntCode, para.context.OrgCode, JsonConvert.SerializeObject(para), this.GetType().Name);

                List<SOModifyBillDTO> soModifyQMDTOList = para.data;
                var org = UFIDA.U9.Base.Context.LoginOrg;
                var groupSOModify = soModifyQMDTOList.Cast<SOModifyBillDTO>().GroupBy(p => p.DocNo);
                foreach (var soModifyList in groupSOModify)
                {
                    var firstSOModifyDTO = soModifyList.First();
                    var result = CreateSOModify(soModifyList.AsEnumerable().ToList());
                }
                return new ApiResult<string>();
            }
        }

        private static string CreateSOModify(List<SOModifyBillDTO> soModifyQMDTOList)
        {
            SOModifyBillDTO soModifyFirst = soModifyQMDTOList[0];
            var org = UFIDA.U9.Base.Context.LoginOrg;
            //创建销售变更单，需要查询出销售变更单，再变更
            var so = SO.Finder.Find("DocNo='" + soModifyFirst.DocNo + "'") ?? throw new Exception("销售订单" + soModifyFirst.DocNo + "不存在");
            PlatformContext context = PlatformContext.Current;
            //查询出销售订单
            UFIDA.U9.ISV.SM.Proxy.CommonQuerySOSRVProxy queryProxy = new CommonQuerySOSRVProxy();
            queryProxy.ContextDTO = new UFIDA.U9.CBO.Pub.Controller.ContextDTOData();
            queryProxy.ContextDTO.UserCode = context.UserCode;
            queryProxy.ContextDTO.EntCode = context.EnterpriseID;
            queryProxy.ContextDTO.CultureName = context.Culture;
            queryProxy.ContextDTO.OrgCode = context.OrgCode;
            queryProxy.SOs = new List<UFIDA.U9.CBO.Pub.Controller.CommonArchiveDataDTOData>();
            var data = new UFIDA.U9.CBO.Pub.Controller.CommonArchiveDataDTOData();
            data.Code = so.DocNo;
            data.ID = so.ID;
            queryProxy.SOs.Add(data);
            var querySOList = queryProxy.Do();
            //关闭
            CloseSOLineSrvProxy closelineSV = new CloseSOLineSrvProxy();
            var closeKeys = new List<SOLineKeyDTOData>();
            closelineSV.SOLineKeyDTOs = closeKeys;
            bool isModify = false;
            foreach (var querySO in querySOList)
            {
                querySO.AutoCreateSOM = true;
                querySO.AutoApproveSOM = true;
                querySO.IsRollBack = true;
                foreach (var modifyLine in soModifyFirst.SOLines)
                {
                    var querySOLine = querySO.SOLines.FirstOrDefault(t => t.DocLineNo == modifyLine.DocLineNo);
                    if (modifyLine.Price == 0)
                    {
                        querySO.SOLines.Remove(querySOLine);
                        if (querySOLine.Status == 3)
                        {
                            closeKeys.Add(new SOLineKeyDTOData
                            {
                                LineKeyDTO = new UFIDA.U9.CBO.Pub.Controller.CommonArchiveDataDTOData
                                {
                                    ID = querySOLine.ID
                                }
                            });
                        }
                        continue;
                    }
                    if (querySOLine != null)
                    {
                        if (querySOLine.TotalMoneyTC != modifyLine.Amount)
                        {
                            querySOLine.PriceCalField = "TotalMoneyTC";
                            querySOLine.TotalMoneyTC = modifyLine.Amount;
                            querySOLine.IsModifyTotalMoneyTC = true;
                            isModify = true;
                        }
                        if (querySOLine.OrderByQtyTU != modifyLine.Qty)
                        {
                            querySOLine.OrderByQtyTU = modifyLine.Qty;
                            isModify = true;
                        }
                        if (querySOLine.FinallyPriceTC != modifyLine.Price)
                        {
                            querySOLine.PriceCalField = "FinallyPrice";
                            querySOLine.IsModifyFinallyPriceTC = true;
                            querySOLine.FinallyPriceTC = modifyLine.Price;
                            querySOLine.IsModifyOrderPriceTC = true;
                            querySOLine.OrderPriceTC = modifyLine.Price;
                            isModify = true;
                            //querySOLine.IsModifyFreeType = true;
                            //querySOLine.FreeType = 1;
                        }
                    }
                    //新增
                    else
                    {
                        querySO.SOLines.Add(new UFIDA.U9.ISV.SM.SOLineDTOData
                        {
                            DocLineNo = modifyLine.DocLineNo,
                            ItemInfo = new ItemInfoData
                            {
                                ItemCode = modifyLine.ItemCode
                            },
                            PriceCalField = "FinallyPrice",
                            OrderByQtyTU = modifyLine.Qty,
                            FinallyPriceTC = modifyLine.Price,
                            TotalMoneyTC = modifyLine.Amount,
                            TaxSchedule = querySO.TaxSchedule,
                            SrcDocType = 0
                        });
                    }
                }

            }
            var proxy = new CommonModifySOSRVProxy();
            proxy.SOs = querySOList;
            try
            {
                if (isModify)
                    proxy.Do(org.ID);
                if (closeKeys.Count > 0)
                    closelineSV.Do();
                return "";
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public ApiResult<string> SNCodeCreate(string[] snCodeList)
        {
            var org = Organization.FindByCode(_orgCode).ID;
            RcvLine rcvLine = RcvLine.Finder.Find($"Receivement.DocNo = 'RCV-2408130001' and ItemInfo.ItemCode = '6801138-BN01-A00'");
            CreateSnAfterDocCreateProxy createSnAfterDocCreateProxy = new CreateSnAfterDocCreateProxy();
            List<SnDocInfoDTOData> list = new List<SnDocInfoDTOData>();
            SnDocInfoDTOData snDocInfoDTOData = new SnDocInfoDTOData();
            snDocInfoDTOData.SnDocDTO = new SnDocDTOData();
            createSnAfterDocCreateProxy.SnDocInfoDTOList = list;
            snDocInfoDTOData.SnDocDTO.Status = 21;
            snDocInfoDTOData.Usetime = DateTime.Now.Date;
            snDocInfoDTOData.UseOrg = Organization.FindByCode(_orgCode).ID;
            snDocInfoDTOData.Wh = rcvLine.Wh.ID;
            snDocInfoDTOData.ItemInfo = rcvLine.ItemInfo.ToEntityData();
            snDocInfoDTOData.SupplyInfo = rcvLine.Receivement.Supplier.ToEntityData();
            snDocInfoDTOData.DocName = "收货单";
            snDocInfoDTOData.DocTypeName = "单据类型";
            snDocInfoDTOData.SnQty = Convert.ToInt32(rcvLine.RtnDeductQtyTU);
            snDocInfoDTOData.StoreUOM = rcvLine.StoreUOM.ID;
            snDocInfoDTOData.StoreUomToBaseRate = 1;
            snDocInfoDTOData.LogisticOrg = org;

            snDocInfoDTOData.SnDocDTO.BizType = 2;
            snDocInfoDTOData.OperatorType = 0;
            snDocInfoDTOData.SnDocDTO.Document.EntityID = rcvLine.Receivement.ID;
            snDocInfoDTOData.SnDocDTO.Document.EntityType = "UFIDA.U9.PM.Rcv.Receivement";
            snDocInfoDTOData.SnDocDTO.DocType.EntityID = rcvLine.Receivement.RcvDocType.ID;
            snDocInfoDTOData.SnDocDTO.DocType.EntityType = "UFIDA.U9.PM.Pub.RcvDocType";
            snDocInfoDTOData.SnDocDTO.DocNo = rcvLine.Receivement.DocNo;
            snDocInfoDTOData.SnDocDTO.DocLineNo = rcvLine.DocLineNo;
            snDocInfoDTOData.SnDocDTO.DocLine = new BizEntityKeyData();
            snDocInfoDTOData.SnDocDTO.DocLine.EntityID = Convert.ToInt64(rcvLine.ID);
            snDocInfoDTOData.SnDocDTO.DocLine.EntityType = "UFIDA.U9.PM.Rcv.RcvLine";

            List<SnDTOData> list2 = new List<SnDTOData>();
            for (int i = 0; i < snCodeList.Length; i++)
            {
                SnDTOData snDTOData = new SnDTOData();
                snDTOData.SnCode = snCodeList[i].Trim();
                if (snDocInfoDTOData != null)
                {
                    snDTOData.SnDocInfoDTO = snDocInfoDTOData;
                }
                list2.Add(snDTOData);
            }
            snDocInfoDTOData.SnDTOList = list2;
            list.Add(snDocInfoDTOData);
            createSnAfterDocCreateProxy.SnDocInfoDTOList = list;
            createSnAfterDocCreateProxy.Do();
            return new ApiResult<string>();
        }
    }
}
